<?php

namespace App\Model;

use Hyperf\Utils\ApplicationContext;
use Hyperf\HttpServer\Contract\RequestInterface;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

class Normal
{

    /**匹配手机号
     * @param string $phoneNumber
     * @return bool
     */
    public function validatePhoneNumber(string $phoneNumber): bool
    {
        $pattern = '/^1[3456789]\d{9}$/';
        return preg_match($pattern, $phoneNumber) === 1;
    }

    public function validateEmail(string $email):bool{
        $pattern = '/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/';
        if (preg_match($pattern, $email)) {
            return true;
        }
        return false;
    }

    /**
     * @param $bankCardNumber
     * @return string
     */
    public function maskBankCard($bankCardNumber,$visibleDigits = 4):string {
        if(strlen($bankCardNumber) <=12){
            return $bankCardNumber;
        }
        $masked = substr($bankCardNumber, 0, 6) . str_repeat('*', strlen($bankCardNumber) - 10) . substr($bankCardNumber, - $visibleDigits);
        return $masked;
    }

    /**
     * @param $idNumber
     * @param $visibleDigits
     * @return string
     */
    public function maskIDNumber($idNumber,$visibleDigits = 4):string {
        $masked = substr($idNumber, 0, 3) . str_repeat('*', strlen($idNumber) - 7) . substr($idNumber, - $visibleDigits);
        return $masked;
    }

    /**生成订单
     * @param $id
     * @param $length
     * @return string
     */
    public function randOrder($id,$length = 12):string{
        return substr(rand(100000, 999999) . time() . $id . rand(1000, 9999), -$length);
    }

    /**获取用户ip
     * @return array|false|mixed|string
     */
    public static function getRealIp($request)
    {
        $userIP = $request->getHeaderLine('x-real-ip');
        if (empty($userIP)) {
            $userIP = $request->getHeaderLine('x-forwarded-for');
        }
        if (empty($userIP)) {
            $userIP = $request->getServerParams()['remote_addr'] ?? '';
        }
        return $userIP;

    }

    /**获取用户是否为手机用户
     * @return bool
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public static function isMobileDevice(): bool
    {
        $request = ApplicationContext::getContainer()->get(RequestInterface::class);
        $userAgent = $request->getHeaderLine('User-Agent');
        $mobileKeywords = [
            'mobile', 'android', 'iphone', 'ipad', 'blackberry', 'windows phone'
        ];
        foreach ($mobileKeywords as $keyword) {
            if (stripos($userAgent, $keyword) !== false) {
                return true;
            }
        }
        return false;
    }

    public function generateChineseTime($time) {
        $chineseUnits = array('点', '分');
        $timeComponents = array('H', 'i');

        $timeString = '';

        for ($i = 0; $i < count($timeComponents); $i++) {
            $timeValue = date($timeComponents[$i], $time);
            // 如果时间部分大于0，则添加到时间字符串中
//            if ($timeValue > 0) {
            $timeString .= $timeValue . $chineseUnits[$i];
//            }
        }

        return $timeString;
    }
    public function getTimeAgo($timestamp) {
        $currentTimestamp = time();
        $diff = $currentTimestamp - $timestamp;

        // 将时间差转换为秒、分钟、小时和天数
        $seconds = $diff;
        $minutes = floor($diff / 60);
        $hours = floor($diff / 3600);
        $days = floor($diff / 86400);

        $timeAgo = '';

        if ($days > 0) {
            $timeAgo = $days . '天前';
        } elseif ($hours > 0) {
            $timeAgo = $hours . '小时前';
        } elseif ($minutes > 0) {
            $timeAgo = $minutes . '分钟前';
        } else {
            $timeAgo = $seconds . '秒前';
        }

        return $timeAgo;
    }

    public function replaceLastSixCharacters($string,$len) {
        $length = strlen($string);
        if ($length < $len) {
            return $string;  // 字符串长度不足六位，直接返回原字符串
        }
        $replacement = '';
        for($i=0;$i<$len;$i++){
            $replacement.='*';
        }
        $newString = substr($string, 0, $length - $len) . $replacement;
        return $newString;
    }

    public static function logger(string $msg,string $group = 'default',string $type= 'info')
    {
        $log_name = $group . date('Y-m-d', time());
        $container = ApplicationContext::getContainer();
        $loggerFactory =$container->get(\Hyperf\Logger\LoggerFactory::class);
        $logger = $loggerFactory->get($log_name, $group);
        $logger->$type($msg);
    }

}
